﻿namespace Huayou.Common
{
    using System;
    using System.Data;
    using System.Data.Odbc;

    public class ODBCAccess : IDisposable
    {
        private OdbcConnection connect;
        private string connectionString;

        public ODBCAccess()
        {
            this.connectionString = "DSN=qdpb";
        }

        public ODBCAccess(string sConnectString)
        {
            this.connectionString = "DSN=qdpb";
            this.connectionString = sConnectString;
        }

        public void Close()
        {
            if ((this.connect != null) && ((this.connect.State != ConnectionState.Broken) && (this.connect.State != ConnectionState.Closed)))
            {
                this.connect.Close();
            }
        }

        public void Dispose()
        {
            if (this.connect != null)
            {
                this.connect.Dispose();
            }
        }

        public int Execute(string myExecuteQuery)
        {
            this.Open();
            OdbcCommand command = new OdbcCommand(myExecuteQuery, this.connect);
            return command.ExecuteNonQuery();
        }

        public static bool IsDBNull(object obj)
        {
            return Convert.IsDBNull(obj);
        }

        public void Open()
        {
            if (this.connect == null)
            {
                this.connect = new OdbcConnection(this.connectionString);
            }
            switch (this.connect.State)
            {
                case ConnectionState.Closed:
                case ConnectionState.Broken:
                    this.connect.ConnectionTimeout = 60;
                    this.connect.Open();
                    break;
            }
        }

        public OdbcDataReader RunProcedure(string SqlString)
        {
            this.Open();
            OdbcCommand command = this.connect.CreateCommand();
            command.CommandText = SqlString;
            command.CommandType = CommandType.Text;
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }

        public DataTable RunProcedure(string SqlString, string TableName)
        {
            this.Open();
            DataTable dataTable = new DataTable();
            dataTable.TableName = TableName;
            OdbcCommand selectCommand = this.connect.CreateCommand();
            selectCommand.CommandText = SqlString;
            selectCommand.CommandType = CommandType.Text;
            OdbcDataAdapter adapter = new OdbcDataAdapter(selectCommand);
            adapter.SelectCommand = selectCommand;
            adapter.Fill(dataTable);
            return dataTable;
        }

        public string ConnectionString
        {
            get
            {
                return this.connectionString;
            }
            set
            {
                this.connectionString = value;
            }
        }
    }
}

